'use strict';

const Service = require('egg').Service;

class AuthApiService extends Service {

  /**
   * 获取所有数据
   */
  async all() {
    const { AuthApi } = this.ctx.model;
    return await AuthApi.findAll();
  }

  /**
   * 创建
   */
  async create() {
    const { AuthApi } = this.ctx.model;
    const {path, type} = this.ctx.w_body()
    // 查询是否有旧数据
    const findData = await AuthApi.findOne({
      path,
      type
    })
    if (findData) {
      throw new Error('不能有相同的API');
    }
    const data = await new AuthApi(this.ctx.w_body()).save();
    const { superId } = this.ctx.w_body();
    if (superId) {
      await AuthApi.addSubNode(superId, data._id);
    }
    return data;
  }

  /**
   * 删除
   */
  async destroy() {
    const { AuthApi } = this.ctx.model;
    const id = this.ctx.params.id;
    const model = await AuthApi.findWithId(id);
    if (model.children.length > 0) {
      throw new Error('子节点必须全部删除, 才能执行当前删除操作');
    }
    return await AuthApi.removeWithId(id);
  }

  /**
   * 修改
   */
  async update() {
    const { AuthApi } = this.ctx.model;
    const id = this.ctx.params.id;
    return await AuthApi.updateWithId(id, this.ctx.w_body());
  }
}

module.exports = AuthApiService;
